#include "../../sdk/wsdk/thread_file_logger.h"



thread_file_logger *thread_file_logger::m_inst=NULL;
recursive_mutex     thread_file_logger::m_lock;

thread_file_logger::thread_file_logger()
{
    m_queue.set_call_backs(this, &thread_file_logger::handle_msg);
    m_queue.thread_begin();
    m_fp = 0;
}

thread_file_logger::~thread_file_logger()
{
    m_queue.thread_syncstop();
    if (m_fp)
    {
        fclose(m_fp);
    }
}

void thread_file_logger::handle_msg(const char *pmsgin, int nsize)
{
    log_msg *pmsg = (log_msg *)pmsgin;
    if (!open_file())
    {
        return;
    }
    //std::cout<<(const char *)pmsg+sizeof(log_msg);
    fwrite((const char *)pmsg+sizeof(log_msg), 1, nsize-sizeof(log_msg), m_fp);
    fflush(m_fp);
}



thread_file_logger *thread_file_logger::get_inst()
{
    recursive_mutex::scoped_lock lock(m_lock);
    if (!m_inst)
    {
        m_inst = new thread_file_logger();
    }
    return m_inst;
}

std::string thread_file_logger::get_time_str()
{
#ifdef _WIN32
    SYSTEMTIME st;
    GetLocalTime ( &st );
    std::ostringstream oss;
    oss<<st.wYear<<st.wMonth<<st.wDay<<"_"<<st.wHour<<st.wMinute<<st.wSecond;
    return oss.str();
#else
    char szBuf[256] =
    { 0 };
    time_t timer = ::time(NULL);
    strftime(szBuf, sizeof(szBuf), "%Y-%m-%d_%H%M%S", localtime(&timer));
    return szBuf;
#endif
}

void thread_file_logger::post_log_msg( std::ostringstream &oss )
{
    log_msg msg;
    std::string str = oss.str();
    msg.size = str.length()+1;
    m_queue.post_msg(&msg, sizeof(log_msg), str.c_str(), msg.size);
}

void thread_file_logger::add_log_prefix(int loglevel, std::ostringstream &oss)
{
    switch (loglevel)
    {
    case 0:
        oss<<"DEBUG-  ";
        break;
    case 1:
        oss<<"INFO-   ";
        break;
    case 2:
        oss<<"WARN-   ";
        break;
    case 3:
        oss<<"ERROR-  ";
        break;
    case 4:
        oss<<"CRITI-  ";
        break;
    default:
        oss<<"CRITI-  ";
        break;
    }
    oss<<get_time_str()<<" ";
}

bool thread_file_logger::open_file()
{
    if (m_fp)
    {
        long length=ftell(m_fp);
        if (length>5242800)
        {
            fclose(m_fp);
            m_fp =NULL;
        }
    }
    if (0==m_fp)
    {
        std::string newfile = "voiceanalyzer" + get_time_str() + ".log";
        m_fp = fopen(newfile.c_str(), "a");
    }
    return m_fp!=0;
}
